package com.markhsiu.minimq.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import com.markhsiu.minimq.core.constant.BaseConfig;
import com.markhsiu.minimq.core.exeption.MiniMQException;
import com.markhsiu.minimq.remote.Address;
import com.markhsiu.minimq.remote.transport.netty.NettyClient;
import com.markhsiu.minimq.remote.transport.talentaio.TalentAioClient;

public abstract class AbstractClientContainer extends BaseConfig{

	protected List<Client> brokers = new ArrayList<>();
	private int mod;
	private boolean single = true;	
	private int transport = NETTY;
	private Address addr;
	private AtomicInteger count = new AtomicInteger(0);
	
	public AbstractClientContainer serverAddress(String host,int port){
		if(!single){
			throw new MiniMQException("非单机模式不允许设置 服务端地址信息");
		}
		addr = new Address(host,port);
		return this;
	}
	
	
	
	/**
	 * 启动客户端
	 */
	public void start() { 
		if(single){
			Client client = null;
			if(transport == TALENTAIO){
				client = new TalentAioClient(addr);
			} else {
				client = new NettyClient(addr);
			}
			
			brokers.add(client);
		} else {
			//zookeeper
		}
		
		init();
		mod = brokers.size();
		for (Client client : brokers) {
			client.open();
			client.connect();
		}
	}
	
	
	
	public abstract void init();
	
	protected Client getClient(){
		return brokers.get(count.getAndIncrement() % mod);
	}
	
	/**
	 * 关闭客户端
	 */
	public void end(){
		for (Client client : brokers) {
			client.close();
		}
	}
	
	public static void main(String[] args) {
		
		int mod = 100;
		
		int  c = 10; 
		long start = System.currentTimeMillis();
		for (int i = 0; i < 100000000; i++) {
			int index = (c++) % mod;
			
		}
		System.out.println((System.currentTimeMillis() - start));
		
		AtomicInteger count = new AtomicInteger(0);
		start = System.currentTimeMillis();
		for (int i = 0; i < 100000000; i++) {
			int index = count.getAndIncrement() % mod;
			
		}
		System.out.println((System.currentTimeMillis() - start));	
		
		Random random = new Random();
		start = System.currentTimeMillis();
		for (int i = 0; i < 100000000; i++) {
			int index = random.nextInt(100) % mod;
			
		}
		System.out.println((System.currentTimeMillis() - start));
		
		
		start = System.currentTimeMillis();
		for (int i = 0; i < 100000000; i++) {
			int index = (int) (System.nanoTime() % mod);
			
		}
		System.out.println((System.currentTimeMillis() - start));
	}
}
